package org.jeecg.common.util.wx;

import org.apache.commons.codec.digest.DigestUtils;
import org.jdom.JDOMException;
import org.jeecg.common.util.ComUtil;

import java.io.IOException;
import java.util.*;

public class UnifiedOrderWxPay {

    /**
     * 发起支付业务
     *
     * @param
     * @return
     * @throws Exception
     */
    public static Map<String, String> toMchPay(String url, SortedMap<String, String> parameters) throws Exception {
        String s = ComUtil.httpPost(url, WXPayUtil.mapToXml(parameters));
        Map<String, String> returnMap = new HashMap<>();
        try {
            //将返回的XML结果再次转换为Map集合
            returnMap = WXPayUtil.xmlToMap(s);
            System.out.println(returnMap);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


    /**
     * 生成签名
     *
     * @param map
     * @return
     */
    public static String getSign(Map<String, String> map) {

        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });

            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + ":" + val + ":");
                    }
                }

            }
            result = sb.toString();
            //进行MD5加密
            result = DigestUtils.md5Hex(result).toUpperCase();
        } catch (Exception e) {
            return null;
        }
        return result;
    }
}
